package com.czlw.module_activity.viewmodel

import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ActivityListBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

class ActivityListViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var currentPage = 0
    val uc = UiChangeEvent()

    class UiChangeEvent {
        val refreshListEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val loadCompleteEvent: SingleLiveEvent<ActivityListBean> = SingleLiveEvent()
    }

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        getCommunities()
    })


    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 0
        getCommunities()
    })

    private fun getCommunities() {
        model.getActivityList(mapOf(
            "areaNo" to model.getAreaId(),
            "pageNum" to (currentPage+1).toString(),
            "pageSize" to "10",
        ))
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ActivityListBean>>() {
                override fun onResult(t: BaseBean<ActivityListBean>) {
                    if (t.code == 200) {
                        currentPage++
                        uc.loadCompleteEvent.postValue(t.data)
                    } else {
                        uc.loadCompleteEvent.postValue(null)
                    }
                }

                override fun onFailed(msg: String?) {
                    showErrorToast(msg)
                    uc.loadCompleteEvent.postValue(null)
                }

            })
    }
}